﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Data;
using WyUnity.Utility.ExtentionMethods;
using WyUnity.Data.Query;
using WyUnity.Utility.Dynamic;
using WyUnity.Data.DataAccess;
using System.Reflection;
using WyUnity.Utility;

namespace WyUnity.Data.TableMapper
{
    /// <summary>
    /// 表映射基类
    /// </summary>
    public abstract class TableBase<T> : ViewBase<T>, ITable
        where T : TableBase<T>
    {
        #region 显示实现接口ITable

        ReadOnlyCollection<FieldDefine> ITable.DefineColumns
        {
            get { return _columns.AsReadOnly(); }
        }

        Columns ITable.ToColumns()
        {
            var col = new Columns();
            foreach (var pg in _propsGetMethodCache)
            {
                if (!pg.Value.MapConfig.DBGenerate)
                {
                    col.Add(pg.Key, pg.Value.Function(this, new object[0]));
                }
            }
            return col;
        }

        WhereClip ITable.GetPrimaryKeyWhereClip()
        {
            WhereClip where = new WhereAll();
            foreach (var k in _keys)
            {
                where = where.And(k, _propsGetMethodCache[k].Function(this, new object[0]));
            }
            return where;
        }


        string IMapObject.GetSQLClip(ISqlDialect dialect)
        {
            return string.Format(dialect.NameFormat, ((ITable)this).GetTableName());
        }
        #endregion

        public override string GetSQLClip()
        {
            return null;
        }
        /// <summary>
        /// 获取表名
        /// </summary>
        public static string GetSQLTableName()
        {
            var t = typeof(T);
            var atts = t.GetCustomAttributes(typeof(MapAttribute), false);
            if (atts.Length > 0)
            {
                var name = (atts[0] as MapAttribute).Name;
                if (!name.IsNullOrEmpty()) return name;
            }
            return t.Name;
        }
        string ITable.GetTableName()
        {
            return GetSQLTableName();
        }

    }
}
